package com.jml.策略模式.重构if判断;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jml.策略模式.重构if判断.msg.mapper.StrategyMapper;
import com.jml.策略模式.重构if判断.msg.mapper.entity.MeiteStrategy;
import com.jml.策略模式.重构if判断.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
public class StrategyContext {
    @Autowired
    private StrategyMapper strategyMapper;

    private Map<String, Class<?>> beans = new ConcurrentHashMap<>();

    public <T> T getStrategy(String strategyId, Class<T> t) {
        // strategyId bean id
        if (StringUtils.isEmpty(strategyId)) {
            return null;
        }
        return SpringUtils.getBean(strategyId, t);
    }

    public <T> T getStrategy(String strategyId, String strategyType, Class<T> t) {

        // strategyId bean id 验证参数
        if (StringUtils.isEmpty(strategyId)) {
            return null;
        }
        if (StringUtils.isEmpty(strategyType)) {
            return null;
        }
        if (t == null) {
            return null;
        }
        Class<?> aClass = beans.get(strategyId);
        if(aClass!=null){
            return (T) aClass;
        }
        // 根据策略id查询
        QueryWrapper<MeiteStrategy> queryWrapper = new QueryWrapper<MeiteStrategy>();
        queryWrapper.eq("strategy_ID", strategyId);
        queryWrapper.eq("strategy_type", strategyType);
        MeiteStrategy meiteStrategy = strategyMapper.selectOne(queryWrapper);
        if (meiteStrategy == null) {
            return null;
        }
        String strategyBeanId = meiteStrategy.getStrategyBeanId();
        if (StringUtils.isEmpty(strategyBeanId)) {
            return null;
        }
        T bean = SpringUtils.getBean(strategyBeanId, t);
        if (bean != null) {
            //存放到HashMap集合中
            beans.put(strategyId, (Class<?>) bean);
        }
        return bean;
    }

}
